
+function() {
	/**
	 * -------------------------------------------------------------<br>
	 * 提交支付<br>
	 * -------------------------------------------------------------<br>
	 * payChannel: 支付渠道(ALIPAY|WECHAT)
	 * paySource: 支付来源(PC|H5), 在微信中会自动变成WX(微信公众号)
	 * data.orderType: 订单类型
	 * data.orderId: 订单编号
	 * userId + dataId: 不传订单号时, 根据userId + dataId唯一确定一条订单记录
	 * data.returnUrl: 同步返回地址(相对路径)
	 * data.notifyUrl: 异步通知地址(相对或绝对路径)
	 * $("button[name=pay]").payment("ALIPAY", "PC", data, [fn]);
	 * -------------------------------------------------------------<br>
	 * @author 赵卉华<br>
	 * date: 2017-10-27<br>
	 * -------------------------------------------------------------<br>
	 */
	$.fn.payment = function(payChannel, paySource, data, options) {
		if ($.isPlainObject(payChannel)) {
			options = paySource; data = payChannel; payChannel = data.payChannel; paySource = data.paySource;
		} else {
			data.payChannel = payChannel; data.paySource = paySource;
		}
		if ($.isFunction(options)) { options = { onSubmit:options }; }

		var o = $.extend(true, {}, $.fn.payment.defaults, options);

		if (data.notifyUrl == "{default}" || !data.notifyUrl && !o.useConfigNotifyUrl) {
			if (data.payChannel == "ALIPAY") {
				data.notifyUrl = o.getBaseUrl("payment/alipay-notify.json");
			} else if (data.payChannel == "WECHAT") {
				data.notifyUrl = o.getBaseUrl("payment/wechat-notify.json");
			}
		} else if (data.notifyUrl == "{config}") {
			data.notifyUrl = undefined; // 采用后台配置的回调地址
		}

		var btn = $(this);
		if (btn.attr("data-paying") == "true") { return; }
		if (data.payChannel == "ALIPAY") {
			o.onReady.call(this, data, o, doAlipaySubmit);
		} else if (data.payChannel == "WECHAT") {
			o.onReady.call(this, data, o, doWechatSubmit);
		}
	};
	var doAlipaySubmit = function(data, o) {
		var self = this;
		var btn = $(self);
		if (o.onSubmit.call(self, data, o) === false) { return; }
		btn.attr("data-paying", true);
		var url = o.getBaseUrl("payment/alipay-prepay.json");
		btn.zajax(url, data, true, {
			succTips: false,
			succ:function(json) {
				btn.attr("data-paying", false);
				if (o.onPayment.call(self, json) === false) { return; }
				var form = json.body.replace(/<script[^>]*>.*<\/script>/, "");
				$('<div style="display:none">'+form+'</div>')
					.appendTo(window.top.document.body)
					.find("form").submit();
			},
			fail: function(json) {
				btn.attr("data-paying", false);
				o.onError.call(self, json);
			}
		});
	};
	var doWechatSubmit = function(data, o) {
		var self = this;
		var btn = $(self);
		if (o.onSubmit.call(self, data, o) === false) { return; }
		btn.attr("data-paying", true);
		var paramsUrl = o.getBaseUrl("payment/wechat-params.json");
		btn.zajax(paramsUrl, data, true, {
			succTips:false,
			succ:function(json) {
				if (json.body.test) { // 测试模式
					var prepayUrl = o.getBaseUrl("payment/wechat-prepay.json");
					btn.zajax(prepayUrl, data, true, {
						succTips:false,
						succ:function(json) {
							btn.attr("data-paying", false);
							if (o.onPayment.call(self, json) === false) { return; }
							window.location.href = json.body.returnUrl;
						},
						fail:function(json) {
							btn.attr("data-paying", false);
						}
					});
				} else {
					if (window.navigator.userAgent.toLowerCase().indexOf("micromessenger") >= 0) {
						data.paySource = "WX"; // 根据userAgent判断, 如果是在微信中, 自动变成WX
					}
					if (data.paySource == "WX") { // 微信公众号支付
						btn.attr("data-paying", false);
						if (o.onPayment.call(self, json) === false) { return; }
						var redirect = location.origin + Utils.getBaseUrl("payment/wechat-prepay.do") + "?" + $.param(data);
						// 微信网页授权
						// https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
						// https://open.weixin.qq.com/connect/oauth2/authorize?appid=...&response_type=code&scope=snsapi_base&state=wechat-pay&redirect_uri=...#wechat_redirect
						var url = json.body.authUrl;
						url += "?appid=" + json.body.appId;
						url += "&response_type=code&scope=snsapi_base&state=wechat-pay";
						url += "&redirect_uri=" + encodeURIComponent(redirect);
						window.location.href = url + "#wechat_redirect";
					} else if (data.paySource == "H5") {
						// 文档 https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=15_4
						var prepayUrl = o.getBaseUrl("payment/wechat-prepay.json");
						btn.zajax(prepayUrl, data, true, {
							succTips:false,
							succ:function(json) {
								btn.attr("data-paying", false);
								if (o.onPayment.call(self, json) === false) { return; }
								window.location.href = json.body.mwebUrl + "&redirect_url=" + encodeURIComponent(json.body.returnUrl);
							},
							fail:function(json) {
								btn.attr("data-paying", false);
							}
						});
					} else if (data.paySource == "PC") {
						var prepayUrl = o.getBaseUrl("payment/wechat-prepay.json");
						btn.zajax(prepayUrl, data, true, {
							succTips:false,
							succ:function(json) {
								btn.attr("data-paying", false);
								if (o.onPayment.call(self, json) === false) { return; }
								var fn = baidu.template(o.qrPayHtml);
								var html = fn($.extend({ zIndex:o.zIndex }, json.body, { returnUrl:json.body.returnUrl }));
								var parent = o.qrPayParent.call(btn.get(0), data, o);
								parent.append(html);
							},
							fail:function(json) {
								btn.attr("data-paying", false);
							}
						});
					}
				}
			},
			fail: function() {
				btn.attr("data-paying", false);
			}
		});
	};
	$.fn.payment.defaults = {
		zIndex: 1000,
		useConfigNotifyUrl: false, // 默认采用后台配置的回调地址
		getBaseUrl: window.Utils && window.Utils.getBaseUrl || function(uri) { return uri; },
		onReady: function(data, options, doSubmit) { // 准备提交, 用于插件扩展
			doSubmit.call(this, data, options);
		},
		onSubmit: function(data) { // 表单提交前事件, 用于具体业务, 返回false将终止表单提交
			return true;
		},
		onPayment: function(json) { // 支付跳转前事件, 用于具体业务, 返回false将终止支付
			return true;
		},
		onError: function(json) {
		},
		qrPayParent: function(data) {
			return $(this).closest(".panel, body");
		},
		qrPayHtml : 
			'<div class="wechat-pay-panel">' +
				'<style>' +
					'.wechat-pay-panel { z-index:<#=zIndex||"auto"#>;box-sizing:border-box;position:fixed;left:0;top:0;width:100%;height:100%;padding:0;overflow:auto;text-align:center;background:rgba(0,0,0,0.1); } ' +
					'.wechat-pay-box { display:inline-block;position:absolute;top:50%;margin-top:-200px;left:50%;margin-left:-150px;padding:20px 40px;background:#FFF;text-align:center; } ' +
					'.wechat-pay-box .title { font-size:1.2em; } ' +
					'.wechat-pay-box .qrimg { width:240px;height:240px; } ' +
				'</style>' +
				'<div class="wechat-pay-box">' +
					'<div class="title">请使用微信扫描二维码完成支付</div>' +
					'<div class="amount">应付金额: <span class="number">¥ <#=totalAmount#></span></div>' +
					'<div>&nbsp;</div>' +
					'<div class="qrimg"><img src="<#=codeImage#>"/></div>' +
					'<div>&nbsp;</div>' +
					'<div class="buttons"><a class="btn btn-default" href="<#=returnUrl#>" >关闭</a>&nbsp;<a href="<#=returnUrl#>" class="btn btn-success">完成</a></div>' +
				'</div>' +
			'</div>'
	};
}();
